<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>汽车之家</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
    <meta name="x5-fullscreen" content="true">
    <meta name="full-screen" content="yes">

    <link rel="stylesheet" type="text/css" href="css/index.css">
    <link rel="stylesheet" href="css/upload.css"/>
    <script type="text/javascript">
        document.documentElement.style.fontSize = window.innerWidth/3.75 + 'px'
    </script>
</head>
<body>

    <section class="bg1">
        <div class="logo"><img src="images/logo.png"></div>
        <div class="upload" id='fileChooseButton'>
            <img src="images/upload.png">
            <input class="upload-file" type="file" id="file" accept="image/*" multiple/>
            <!-- <input type="file" class="upload_file" id="choose" accept="image/*" multiple> -->
            <!-- <ul class="photos">
                <li></li>
            </ul> -->
            <img id="previewResult"/>
            <img id="needCropImg" />
            
        </div>

        <!-- <div class="up_btn">
            <a id="upload" href="javascript:;">
              <img src="images/up_c1.png">
            </a>
        </div> -->
        <div class="up_btn2">
            <a href="javascript:;">传完了，赶紧测试</a>
        </div>
    </section>
    <div class="myMask"></div>
    <div class="app" id="uploadPage">
        <div class="upload-loading">
            <span class="centerXY"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i></span>
        </div>
        <div class="main">
            <canvas class="upload-mask">

            </canvas>
            <div class="preview-box">
                <img id="preview"/>
            </div>
            <canvas class="photo-canvas">

            </canvas>
            <div class="bar">
              <a id="getFile" class="pull-right">完成</a>
            </div>
        </div>
    </div>
</body>
<script src="js/require.js" ></script>
<script src="js/main.js"></script>
<script src="js/canvas-toBlob.js"></script>
<script>

    var myCrop;
    //防require缓存
    require.config({
        urlArgs:"bust="+new Date
    })
    require(["jquery",'hammer','tomPlugin',"tomLib",'hammer.fake','hammer.showtouch'],function($,hammer,plugin,T){
        document.addEventListener("touchmove",function(e){
            e.preventDefault();
        })
        //初始化图片大小300*300
        var opts={cropWidth:300,cropHeight:300},
                $file=$("#file"),
                previewStyle={x:0,y:0,scale:1,rotate:0,ratio:1},
                transform= T.prefixStyle("transform"),
                transition= T.prefixStyle("transition"),
                transitionend=T.prefixEvent('transitionEnd'),
                $previewResult=$("#previewResult"),
                $previewBox=$(".preview-box"),
                $rotateBtn=$("#rotateBtn"),
                $getFile=$("#getFile"),
                $preview=$("#preview"),
                $uploadPage=$("#uploadPage"),
                $mask=$(".upload-mask"),
                $loading=$(".upload-loading"),
                maskCtx=$mask[0].getContext("2d"),
                $needCropImg=$("#needCropImg"),
                myCropInfo,backX,backY,maxOffset=40;

        //这是插件调用主体
        myCrop=T.cropImage({
            bindFile:$file,//绑定Input file
//            bindFile:$needCropImg[0],//绑定一个图片
            enableRatio:true,//是否启用高清,高清得到的图片会比较大
            canvas:$(".photo-canvas")[0],  //放一个canvas对象
            cropWidth:opts.cropWidth,       //剪切大小
            cropHeight:opts.cropHeight,
            bindPreview:$preview,      //绑定一个预览的img标签
            useHammer:true,            //是否使用hammer手势，否的话将不支持缩放
            oninit:function(){

            },
            onChange:function(){
                $loading.show();
                resetUserOpts();
            },
            onLoad:function(data){
                //用户每次选择图片后执行回调
                previewStyle.ratio=data.ratio;
                $preview.attr("src",data.originSrc).css({width:data.width,height:data.height}).css(transform,'scale('+1/previewStyle.ratio+')');
                myCrop.setCropStyle(previewStyle)
                $loading.hide();
                myCropInfo=myCrop.getCropInfo();
            }
        });
        function resetUserOpts(){
            $(".photo-canvas").hammer('reset');
            previewStyle={scale:1,x:0,y:0,rotate:0};
            $previewResult.attr("src",'').hide();
            $preview.attr("src",'')
        }
        $('#fileChooseButton').on('click',function(){
            // setTimeout(function(){
            //     resetUserOpts();
            // })
        });
        $(".photo-canvas").hammer({
            minScale:1,
            dragendCb:function(){
                var transformStr=$preview.css(transform).replace(/\s/g,'');
                //获取matrix矩阵后两位 x y替换掉
    transformStr=transformStr.replace(/((-?\d+)?(\.\d+)?),((-?\d+)?(\.\d+)?)\)$/,(backX!=null?backX:'$1')+','+(backY!=null?backY:'$4')+')');
                    if(backX!=null){
                        previewStyle.x=backX/previewStyle.ratio
                    }
                    if(backY!=null){
                        previewStyle.y=backY/previewStyle.ratio
                    }
                $(".photo-canvas").hammer('setLastPos',{x:previewStyle.x,y:previewStyle.y})
                $preview.one(transitionend,function(){
                    $preview.css('transition','')
                })
                $preview.css({transition:'all 0.3s',
                        transform:transformStr});
                
            },
            gestureCb:function(o){
                //每次缩放拖拽的回调
                var G=Object.assign({},o,{ratio:previewStyle.ratio})
                 G.y*=G.ratio;
                 G.x*=G.ratio;
                 // lx<0 myCropInfo.x*G.scale+G.x<0
                 // rx>0 -myCropInfo.x*G.scale+G.x>0
                 // ty -myCropInfo.y*G.scale-G.y>0
                 // by myCropInfo.y*G.scale+G.y<0
                backX=backY=null;
                // G.rotate=0;//不旋转了
                var sx=myCropInfo.dWidth/G.ratio*G.scale/2-opts.cropWidth/2;
                var sy=myCropInfo.dHeight/G.ratio*G.scale/2-opts.cropHeight/2;
                //到达最大边缘则在最大基础上再扩展maxOffset距离,后面动画弹回
                    if(-sy+G.y>0){
                        backY=sy;
                        if(-sy+G.y>maxOffset){
                            G.y=sy+maxOffset;
                        }
                    }
                    if(sy+G.y<0){
                        backY=-sy;
                         if(sy+G.y<-maxOffset){
                            G.y=-sy-maxOffset;
                        }
                    }
                    if(-sx+G.x>0){
                        backX=sx;
                         if(-sx+G.x>maxOffset){
                            G.x=sx+maxOffset;
                        }
                    }
                    if(sx+G.x<0){
                        backX=-sx;
                         if(sx+G.x<-maxOffset){
                            G.x=-sx-maxOffset;
                        }
                    }
                    $preview.css(transform,"translate3d("+ G.x+'px,'+ G.y+"px,0) rotate("+G.rotate+"deg) scale("+(G.scale/G.ratio)+")")
                    G.x/=G.ratio;
                    G.y/=G.ratio;
                    Object.assign(previewStyle,G);
            }
        })
        //选择图片
        $rotateBtn.on("click",function(){
            previewStyle.rotate+=90;
            if(previewStyle.rotate>=360){
                previewStyle.rotate-=360;
            }
            $(".photo-canvas").hammer('setRotate',previewStyle.rotate)
            myCrop.setCropStyle(previewStyle)
            $preview.css(transform,"translate3d("+ previewStyle.x+'px,'+ previewStyle.y+"px,0) rotate("+previewStyle.rotate+"deg) scale("+(previewStyle.scale/previewStyle.ratio)+")")
        })
        //获取图片并关闭弹窗返回到表单界面
        $getFile.on("click",function(){
            $('.myMask').hide();
            var cropInfo;
            $uploadPage.hide();
            myCrop.setCropStyle(previewStyle)
            //自定义getCropFile({type:"png",background:"red",lowDpi:true})
            cropInfo=myCrop.getCropFile({});
            $previewResult.attr("src",cropInfo.src).show();
            console.log(previewStyle,cropInfo)
            localStorage.setItem('header_img',cropInfo.src);
            //尝试传参后台裁剪
            var form=new FormData();
            // var previewFactor=cropInfo.oWidth/
            form.append('dwidth',cropInfo.dWidth*previewStyle.ratio)
            form.append('dheight',cropInfo.dHeight*previewStyle.ratio)
            form.append('offsetX',previewStyle.x*previewStyle.ratio)
            form.append('offsetY',previewStyle.y*previewStyle.ratio)
            form.append('cwidth',opts.cropWidth*previewStyle.ratio)
            form.append('cheight',opts.cropHeight*previewStyle.ratio)
            form.append('scale',(previewStyle.scale/previewStyle.ratio))
            form.append('imgFile',cropInfo.file)
            form.append('rotate',-1*previewStyle.rotate);
//            $.ajax({
//                url:"./testCrop.php",
//                type:'post',
//                data:form,
//                processData:false,
//                contentType: false,
//                dataType:"json",
//                success:function(data){
//                    console.log(data)
//                    if(data.result==1){
//                        console.log(data.imgPath)
//                    }
//                }
//            })
            //可选传base64或者file对象
            //cropInfo.src cropInfo.dfd

            //you can upload img base64  :cheers:)
//            console.info('拿到Base64了,传给后台吧？' + src)//src.substr(22)
       /*     $.ajax({
                url:'http://127.0.0.1/testAdjustImg/upload.php',
                type:"post",
                dataType:"json",
                data:{base64:cropInfo.src.substr(22),uploadType:'base64'},//后端无需在过滤头
                success:function(data){
                    if(data.result==1){
                        console.log(data.imgPath)
                    }
                }
            })*/
            //you can upload new img file :cheers:)
//            cropInfo.dfd.done(function(blob){
//                if(blob){
//                    var formData=new FormData;
//                    blob.name='imgFile'
//                    formData.append("imgFile",blob)
//                    formData.append("uploadType",'imgFile');
//                    $.ajax({
//                        url:'./upload.php',
//                        type:"post",
//                        data:formData,
//                        processData:false,
//                        contentType: false,
//                        dataType:"json",
//                        success:function(data){
//                            console.log(data)
//                            if(data.result==1){
//                                console.log(data.imgPath)
//                            }
//                        }
//                    })
//                }
//            })

        })
        //上传文件按钮&&关闭弹窗按钮
        $(document).delegate("#file","click",function(e){
            $('.myMask').show();
            $uploadPage.show();
        }).delegate("#closeCrop","click",function(){
            $uploadPage.hide();
            resetUserOpts();
            myCrop.setCropStyle(previewStyle)
        })
        $file.one("click",showCropModal)
        $previewResult.on('click',function(){
            $('.myMask').show();
            showCropModal();
        })

        function showCropModal(){
            setTimeout(function(){
                $uploadPage.show();
                $mask.prop({width:$mask.width(),height:$mask.height()})
                maskCtx.fillStyle="rgba(0,0,0,0.7)";
                maskCtx.fillRect(0,0,$mask.width(),$mask.height());
                maskCtx.strokeStyle='white';
                maskCtx.lineWidth='2'
                maskCtx.clearRect(($mask.width()-opts.cropWidth)/2,($mask.height()-opts.cropHeight)/2,opts.cropWidth,opts.cropHeight)
                maskCtx.strokeRect(($mask.width()-opts.cropWidth)/2-1,($mask.height()-opts.cropHeight)/2-1,opts.cropWidth+2,opts.cropHeight+2);//Add a subpath with four points
            })
        }
        $('.up_btn2 a').click(function(){
            var header_img = $('#previewResult').attr('src');

            if(header_img) {
                window.location.href='two.html'
            } else {
                alert('请上传图片');
            }
        });
        document.addEventListener('touchmove', function(e){e.preventDefault()}, false);

        //单独绑定图片时用到
//        $needCropImg[0].addEventListener("load",showCropModal)
//        $needCropImg[0].src='./img/9-1.jpg';
    })
</script>
<!-- <script src="js/index.js"></script> -->
<!-- <script>

    $('.change_img img').click(function (){
        $('.cover').show();
        $(this).addClass('active').siblings().removeClass('active');
        setTimeout(function (){
            $('.cover').hide();
        }, 3000);
    })


  var filechooser = document.getElementById("choose");
  //    用于压缩图片的canvas
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext('2d');
  //    瓦片canvas
  var tCanvas = document.createElement("canvas");
  var tctx = tCanvas.getContext("2d");
  var maxsize = 100 * 1024;
  $("#upload").on("click", function() {
        filechooser.click();
      })
      .on("touchstart", function() {
        $(this).addClass("touch")
      })
      .on("touchend", function() {
        $(this).removeClass("touch")
      });
  filechooser.onchange = function() {
    if (!this.files.length) return;
    var files = Array.prototype.slice.call(this.files);
    if (files.length > 1) {
      alert("最多同时只可上传1张图片");
      return;
    }
    files.forEach(function(file, i) {
      if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
      var reader = new FileReader();
      // var li = document.createElement("li");
      var li = $('.photos li');
        //获取图片大小
      var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
      // $(".photos").append($(li));
      reader.onload = function() {
        var result = this.result;
        var img = new Image();
        img.src = result;
        $(li).css("background-image", "url(" + result + ")");
        //如果图片大小小于100kb，则直接上传
        if (result.length <= maxsize) {
          img = null;
          upload(result, file.type, $(li));
          return;
        }
        //图片加载完毕之后进行压缩，然后上传
        if (img.complete) {
          callback();
        } else {
          img.onload = callback;
        }
        function callback() {
          var data = compress(img);
          upload(data, file.type, $(li));
          img = null;
        }
      };
      reader.readAsDataURL(file);
    })
  };
  //    使用canvas对大图片进行压缩
  function compress(img) {
    var initSize = img.src.length;
    var width = img.width;
    var height = img.height;
    //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
    var ratio;
    if ((ratio = width * height / 4000000) > 1) {
      ratio = Math.sqrt(ratio);
      width /= ratio;
      height /= ratio;
    } else {
      ratio = 1;
    }
    canvas.width = width;
    canvas.height = height;
//        铺底色
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    //如果图片像素大于100万则使用瓦片绘制
    var count;
    if ((count = width * height / 1000000) > 1) {
      count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
//            计算每块瓦片的宽和高
      var nw = ~~(width / count);
      var nh = ~~(height / count);
      tCanvas.width = nw;
      tCanvas.height = nh;
      for (var i = 0; i < count; i++) {
        for (var j = 0; j < count; j++) {
          tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
          ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
        }
      }
    } else {
      ctx.drawImage(img, 0, 0, width, height);
    }
    //进行最小压缩
    var ndata = canvas.toDataURL('image/jpeg', 0.1);
    console.log('压缩前：' + initSize);
    console.log('压缩后：' + ndata.length);
    console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
    tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      localStorage.setItem("header_img", ndata);
    return ndata;
  }
  //    图片上传，将base64的图片转成二进制对象，塞进formdata上传
  function upload(basestr, type, $li) {
    var text = window.atob(basestr.split(",")[1]);
    var buffer = new Uint8Array(text.length);
    var pecent = 0, loop = null;
    for (var i = 0; i < text.length; i++) {
      buffer[i] = text.charCodeAt(i);
    }
    var blob = getBlob([buffer], type);
    var xhr = new XMLHttpRequest();
    var formdata = getFormData();
    formdata.append('imagefile', blob);
    xhr.open('post', '/cupload');
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var jsonData = JSON.parse(xhr.responseText);
        var imagedata = jsonData[0] || {};
        var text = imagedata.path ? '上传成功' : '上传失败';
        console.log(text + '：' + imagedata.path);
        clearInterval(loop);
        //当收到该消息时上传完毕
        $li.find(".progress span").animate({'width': "100%"}, pecent < 95 ? 200 : 0, function() {
          $(this).html(text);
        });
        if (!imagedata.path) return;
        $(".pic-list").append('<a href="' + imagedata.path + '">' + imagedata.name + '（' + imagedata.size + '）<img src="' + imagedata.path + '" /></a>');
      }
    };
    //数据发送进度，前50%展示该进度
    xhr.upload.addEventListener('progress', function(e) {
      if (loop) return;
      pecent = ~~(100 * e.loaded / e.total) / 2;
      $li.find(".progress span").css('width', pecent + "%");
      if (pecent == 50) {
        mockProgress();
      }
    }, false);
    //数据后50%用模拟进度
    function mockProgress() {
      if (loop) return;
      loop = setInterval(function() {
        pecent++;
        $li.find(".progress span").css('width', pecent + "%");
        if (pecent == 99) {
          clearInterval(loop);
        }
      }, 100)
    }
//    xhr.send(formdata);

  }
  /**
   * 获取blob对象的兼容性写法
   * @param buffer
   * @param format
   * @returns {*}
   */
  function getBlob(buffer, format) {
    try {
      return new Blob(buffer, {type: format});
    } catch (e) {
      var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
      buffer.forEach(function(buf) {
        bb.append(buf);
      });
      return bb.getBlob(format);
    }
  }
  /**
   * 获取formdata
   */
  function getFormData() {
    var isNeedShim = ~navigator.userAgent.indexOf('Android')
        && ~navigator.vendor.indexOf('Google')
        && !~navigator.userAgent.indexOf('Chrome')
        && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
    return isNeedShim ? new FormDataShim() : new FormData()
  }
  /**
   * formdata 补丁, 给不支持formdata上传blob的android机打补丁
   * @constructor
   */
  function FormDataShim() {
    console.warn('using formdata shim');
    var o = this,
        parts = [],
        boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
        oldSend = XMLHttpRequest.prototype.send;
    this.append = function(name, value, filename) {
      parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
      if (value instanceof Blob) {
        parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
        parts.push(value);
      }
      else {
        parts.push('\r\n\r\n' + value);
      }
      parts.push('\r\n');
    };
    // Override XHR send()
    XMLHttpRequest.prototype.send = function(val) {
      var fr,
          data,
          oXHR = this;
      if (val === o) {
        // Append the final boundary string
        parts.push('--' + boundary + '--\r\n');
        // Create the blob
        data = getBlob(parts);
        // Set up and read the blob into an array to be sent
        fr = new FileReader();
        fr.onload = function() {
          oldSend.call(oXHR, fr.result);
        };
        fr.onerror = function(err) {
          throw err;
        };
        fr.readAsArrayBuffer(data);
        // Set the multipart content type and boudary
        this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
        XMLHttpRequest.prototype.send = oldSend;
      }
      else {
        oldSend.call(this, val);
      }
    };
  }
</script> -->
</html>